<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></script>

</head>
<body>
    <div id="app">
        <div v-if= 'books.length'>
            <table>
                <thead>
                    <tr>
                        <th></th>
                        <th>编号</th>
                        <th>书名</th>
                        <th>价格</th>
                        <th>购买数量</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for='(item, index) in books'>
                        <td>{{item.id}}</td>
                        <td>{{item.name}}</td>
                        <td>{{item.price | showPrice}}</td>
                        <td>
                            <button @click = 'decrement(index)' :disabled = 'item.num < 1'>-</button>
                            {{item.num}}
                            <button @click = 'increment(index)'>+</button>
                        </td>
                        <td>
                            <button @click = 'move(index)'>移除</button>
                        </td>
                    </tr>
                </tbody>
            </table>
            <h2>总价:{{total | showPrice}}</h2>
        </div>
        <div v-else>
            <h2>购物车为空</h2>
        </div>
    </div>
</body>
<script>
    let vm = new Vue({
        el: '#app',
        data:{
            books: [{
                id: 0,
                name: '伏天氏',
                price: 80,
                num: 1
            },
            {
                id: 1,
                name: '终极斗罗',
                price: 50,
                num: 1
            },
            {
                id: 2,
                name: '绝世武魂',
                price: 90,
                num: 1
            },
            {
                id: 3,
                name: '元尊',
                price: 70,
                num: 1
            }]
        },
        methods: {
            decrement(index) {
                this.books[index].num--
            },
            increment(index) {
                this.books[index].num++
            },
            move(index){
                this.books.splice(index, 1)
            }
        },
        filters: {
            // 保留两位小数
            showPrice(price) {
                return '¥' + price.toFixed(2)
            }
        },
        computed: {
            total(){
                let result = 0
                for(let i = 0 ; i < this.books.length ; i++){
                   result += this.books[i].price * this.books[i].num 
                }
                return result
            }

        }
    })
</script>

<!-- 
    总结:
    这个案例用到了 v-for v-on(@) v-bind(:) v-if conputed(计算属性) methods(方法) disabled(按钮禁用) .toFixed(保留几位小数)
 -->
</html>